# Copyright (C) 2006  Apptility LLC  http://www.apptility.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA


# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
   include LoginEngine
   include UserEngine

    
   $MAIN_TAB_ORDER_MAP = UIFContainer.instance.main_tab_order_map
   $MAIN_TABS_ARRAY = UIFContainer.instance.navtabsarray
   $MAIN_TABS_HASH = UIFContainer.instance.navtabshash
   
   def getLatestBlogs(feedurl)
    require 'feed_tools' 
    @h = getFeed(feedurl)
   end
   
   def getFeed(feedurl)
        @feedu = nil
        @error_string = ""
        begin
          @feedu = FeedTools::Feed.open(feedurl) 
          @error_string = nil
        rescue => err
          @error_string << err.message
          AjubyLogger.logInfo "##########Error message :" << err.message
        end  
        # fArray = Array.new(@feedu, @error_string)
        h = {'feedobj' => @feedu, 'errorstr' => @error_string}
        return h
   end


   def trimstring(string, collength)
      if(string.length>collength)
        return string[0,collength]+"...."
      else
        return string
      end    
   end

   def is_enterprise_admin
    if current_user.is_enterprise =='y'
      return true
    else
      return false
    end    
   end
   
   
   def isodd(input_val) 
     #x = input_val mod 2
     x = input_val % 2
     if x == 1
        return true;
     else
        return false;
     end
   end  
  
   def canRequestLink(controller, action)
    if authorized?(:controller => controller, :action => action) 
      return true
    else
      return false  
    end
   end
 
   def renderLeftColumn(currentTopLink)
      subtabstr = ""
      subtabstr = "#{getLeftColumnhtml(currentTopLink)}"
      return subtabstr
   end
   
   def renderTopNavLinks()
      @id =""
      @action ="edit_user"
      if(current_user!=nil)
        @id = current_user.id
        @action =   "#{@action}/#{@id}"
      end
      
      @myaccount_string=""
      if canRequestLink('user', 'edit_user')
        @myaccount_string  = "<a href='/user/#{@action}'>My Account</a>"
      end  
        
      
      subtabstr = ""
      subtabstr =  "#{getNavLinkhtml('user', 'logout', 'Logout')}" +
                   "#{getNavLinkhtml('controlpanel', 'list', 'Control Panel')}" +    
                   @myaccount_string
                   
      return subtabstr
   end
   
   
   def renderMainTabs(currentTab)
    tabstr=""
    
    #$MAIN_TABS_ARRAY.each {|tab|
    #AjubyLogger.logInfo ">>>>>>>>>>>>>>> : #{$MAIN_TAB_ORDER_MAP}"
    $MAIN_TAB_ORDER_MAP.sort
    #AjubyLogger.logInfo ">>>>>>>>>>>>>>> : #{$MAIN_TAB_ORDER_MAP}"
    
    $MAIN_TAB_ORDER_MAP.each_key{|order_key|
       tab = $MAIN_TAB_ORDER_MAP[order_key]    
       @tabname = tab.tabname
       @subtabshash = tab.subtabshash 
       # You always should this.self node attached to the tab
       # in yaml file, else this will not work.
       @tabselfarray = @subtabshash["this.self"]
       @tabselfhash = @tabselfarray[0]
       @maintabcontroller = @tabselfhash["controller"]
       @maintabaction = @tabselfhash["action"]
       if(@tabname==currentTab)
        tabstr = tabstr + "#{gettabhtml('true', @maintabcontroller, @maintabaction, currentTab)}"
       else
        tabstr = tabstr + "#{gettabhtml('false', @maintabcontroller, @maintabaction, @tabname)}"
       end
      }   
    return  tabstr
   end
    
   def renderSubTabs(mainTab, currentSubTab)
    subtabstr=""
    @params_hash_up = ge_subtab_params
    #AjubyLogger.logInfo "##########params_hash_up:  #{@params_hash_up} / #{@params_hash_up['cid']}"
    
    @array_subtab_elements = $MAIN_TABS_HASH[mainTab]
    @subtabnames = @array_subtab_elements[0]
    @tab_order_map = @array_subtab_elements[1]
    # We need to sort the @tab_order_map first on its key. 
    # which is 'order' element of the subtab
    @subtabcount_t = 0;
    @tab_order_map.each_key {|tab_order|
      @sub_tab_name = @tab_order_map[tab_order]
      subtabelement = @subtabnames[0]
      @subtabvalues = subtabelement[@sub_tab_name]
           @subtabvalues.each {|subtabvalue|
              
              @subtabaction = subtabvalue["action"]
              @subtabcontroller = subtabvalue["controller"]
              #AjubyLogger.logInfo "@subtabaction:  #{@subtabaction}, @subtabcontroller: #{@subtabcontroller}"
              @params_array = subtabvalue["params"]
              @params_str = ""
              if(@params_array!=nil)
                 @params_array.each {|params_hash|
                    params_hash.each_key{|params_key|
                      if(@params_str=="")
                        @params_str = "?"+"#{params_key}=#{@params_hash_up[params_key]}"
                      else
                        @params_str = @params_str + "&" + "#{params_key}=#{@params_hash_up[params_key]}"
                      end
                    }
                  }
                  #AjubyLogger.logInfo "params=>#{@params_str}"
              end
              
              @isCurrentSubtabMatch = "false"
              @isLastTab = false
              if(@sub_tab_name==currentSubTab)
                @isCurrentSubtabMatch = "true"
              end
              
              @subtabcount_t = @subtabcount_t + 1   
              if (@subtabcount_t==(@tab_order_map.size))
                @isLastTab = true
              end
              #AjubyLogger.logInfo "############COUNT: #{subtabelement.size} / #{@subtabcount_t}"
              
              if(@params_str=="")
                subtabstr = subtabstr + "#{getsubtabhtml(@isCurrentSubtabMatch, @subtabcontroller, @subtabaction, @sub_tab_name,@isLastTab)}"
              else
                subtabstr = subtabstr + "#{getsubtabhtml_p(@isCurrentSubtabMatch, @subtabcontroller, @subtabaction, @sub_tab_name, @params_str, @isLastTab)}"
              end                      
                        
            }
 
      
    }   
    return  subtabstr
   end

   def getLeftColumnhtml(currentTopLink)
      newuserparams = ""
      if(current_user!=nil)
        @current_org_id = current_user.organization_id
        newuserparams = "?cid=#{@current_org_id}"
      end
          
      
      if(currentTopLink=='My account')    
        strt = renderLeftColumnLink('user','list',nil, 'User list') +
               renderLeftColumnLink('user','new', newuserparams, 'New user')
               
        if(is_enterprise_admin)
          strt = strt + renderLeftColumnLink('organization','list',nil, 'Company list')
        end      
         
      end 
      if strt!=nil
        return strt
      else
        return ""
      end
   end
   
   def getNavLinkhtml(controller, action, currentTab)
      strt = renderNavLink(controller, action, currentTab)
      if strt!=nil
        return strt
      else
        return ""
      end
   end
   
   
   def gettabhtml(iscurrent, controller, action, currentTab)
      strt = renderMainTab(iscurrent, controller, action, currentTab)
      if strt!=nil
        #AjubyLogger.logInfo "#gettabhtml: #{strt}" 
        return strt
      else
        return ""
      end
   end

      
   def getsubtabhtml_p(iscurrent, controller, action, currentTab, extraparams, ilst)
      #AjubyLogger.logInfo "#getsubtabhtml2 => #{currentTab}"
      strt = renderSubTab(iscurrent, controller, action, currentTab,extraparams, ilst)
      if strt!=nil
        #AjubyLogger.logInfo "#gettabhtml: #{strt}" 
        return strt
      else
        return ""
      end
   end


   def getsubtabhtml(iscurrent, controller, action, currentTab, ilst)
      #AjubyLogger.logInfo "#getsubtabhtml1 => #{currentTab}"
      getsubtabhtml_p(iscurrent, controller, action, currentTab, "", ilst)
   end
        
     def renderLeftColumnLink(controller, action, params, linkTitle)
      if canRequestLink(controller, action)
        return "<p><a href='/#{controller}/#{action}#{params}'>#{linkTitle}</a></p>"
      end  
     end
     
     def renderNavLink(controller, action, tabtitle)
      if canRequestLink(controller, action)
        return "<a href='/#{controller}/#{action}'>#{tabtitle}</a>"
      end  
   end  
     
   def renderMainTab(iscurrent, controller, action, tabtitle)
      if canRequestLink(controller, action)
        iscurrentstr = ""
        if iscurrent!=nil and iscurrent=='true'
          iscurrentstr = "id='current'"
        end
        return "<li #{iscurrentstr}><a href='/#{controller}/#{action}'><span>#{tabtitle}</span></a></li>"
      end  
   end  

   def renderSubTab(iscurrent, controller, action, tabtitle, ilst)
    AjubyLogger.logInfo "renderSubTab1 -> #{tabtitle}"
    renderSubTab(iscurrent, controller, action, tabtitle, "", ilst)
   end
   
   def renderSubTab(iscurrent, controller, action, tabtitle, extraparams, isLastTab)
      #AjubyLogger.logInfo "renderSubTab2 -> #{tabtitle}"
      tabseperator=" | "
      if(isLastTab)
        tabseperator=""
      end
        
      if canRequestLink(controller, action)
        return "<li><a href='/#{controller}/#{action}#{extraparams}'>#{tabtitle}"+tabseperator+"</a></li>" 
       end
        
   end  
   
   def ge_subtab_params
    @params_hash = Hash.new
    if(current_user!=nil)
       @params_hash["cid"] = current_user.organization_id
    end
    return @params_hash
   end
   
   def renderSearchPanel(form_parameter_map, search_element_list)
      @searchPanelStr = ""
      @searchElementStr =""
      search_element_list.each {|search_element|
        @type = search_element["type"]
        if(@type==nil)
          @type="text"
        end
        @label = search_element["label"]
        if(@label==nil)
          return "<font color='red'>Label not provided for search element in search panel rendering..</font>"
        end  
        @name = search_element["name"]
        if(@name==nil)
          @name = @label
        end
        @size = search_element["size"]
        if(@size==nil)
          @size = "10"
        end
        @searchElementStr = @searchElementStr + "\n&nbsp;#{@label}&nbsp; <input type='#{@type}' name='#{@name}' size='#{@size}'/>"
      }
      
      @searchElementStr = @searchElementStr +  '&nbsp;&nbsp;<input type="image" src="/themes/odotclassic/images/btn_search.png" name="submitbutton" value=""/>'
      
      @form_tag_str = ""
      @form_controller = form_parameter_map["controller"]
      @form_action = form_parameter_map["action"]
      @action = "";
      if(@form_controller!=nil)
        @action = @action + @form_controller
      end
      if(@form_action!=nil)
        @action = @action + "/" +@form_action
      end
      if (@action==nil)
        @action="search"
      end
      @action= "/"+@action
          
      @form_method = form_parameter_map["method"]
      if (@form_method==nil)
        @form_method="post"
      end
      @form_tag_str = "<form action='#{@action}' name='searchform' method='#{@form_method}'>" 
      
      @searchPanelStr = '<div class="genericform">'
      @searchPanelStr = @searchPanelStr + @form_tag_str
      @searchPanelStr = @searchPanelStr + '<table><th style = "text-align:left; font-size:13px">Search<br></th><tr class="genericform"><td>'
      @searchPanelStr = @searchPanelStr + @searchElementStr
      @searchPanelStr = @searchPanelStr + '</td></tr></table><br/></div></form>'
      return @searchPanelStr
   end
   
   def renderBasicListPanel(columns_to_display, model_list, enable_pagination, pagination_model_list, options)
      return renderBasicListPanel_w_a_o(columns_to_display, model_list, enable_pagination, pagination_model_list, options)
   end    
   
   
   def renderBasicListPanel_w_a_o(columns_to_display, model_list, enable_pagination, pagination_model_list, options)
      @listPanelStr ="" # "<form name='listform'>\n"
      @listPanelStr = @listPanelStr + "<div class='list'>\n<table>\n"
      if(enable_pagination)
        @listPanelStr = @listPanelStr + "<tr><td class='pagination' colspan='#{columns_to_display.size+1}'>\n"
        pagination_html = pagination_links(pagination_model_list)
        if(pagination_html==nil)
        	pagination_html = ""
        end
	@listPanelStr = @listPanelStr + pagination_html        
        @listPanelStr = @listPanelStr + "</td></tr>\n"
      end
      for column in columns_to_display
        @listPanelStr = @listPanelStr + "<th>#{column.human_name}</th>\n"
      end  

      @show_action = true      
      if(options!=nil and options['show_action']=='false')
        @show_action = false
      end
      if @show_action
        @listPanelStr = @listPanelStr + "<th>Actions</th>\n"  
      end  
      count=1
      rowtype="odd"
      for @model in model_list
        rowtype = get_row_type(count)

        @listPanelStr = @listPanelStr + "<tr class='#{rowtype}'>\n"
        for column in columns_to_display
          @listPanelStr = @listPanelStr + "<td>#{trimstring(@model.send(column.name),50)}</td>\n"
        end
        
        if @show_action
          @listPanelStr = @listPanelStr + "<td>\n"
          @listPanelStr = @listPanelStr + "&nbsp;#{link_if_authorized image_tag('/themes/odotclassic/images/show.png', :title => 'Details'), {:action => 'show', :id => @model}}"
          @listPanelStr = @listPanelStr + "&nbsp;#{link_if_authorized image_tag('/themes/odotclassic/images/edit.png', :title => 'Edit'), {:action => 'edit', :id => @model}}"
        
          @delete_string = "delete"
          if options!=nil
            @delete_alias = options['delete_alias']
            if(@delete_alias!=nil)
              @delete_string = @delete_alias
            end 
          end   
          @listPanelStr = @listPanelStr + "&nbsp;#{link_if_authorized image_tag('/themes/odotclassic/images/delete.png', :title => 'Delete') , {:action => @delete_string , :id => @model} , {:confirm => 'Are you sure you want to delete?'}}"

        end
        
        if(@options!=nil)
          # options code goes here...
        end
        
#        if authorized?(:action => 'delete') && (current_user.login != UserEngine.config(:admin_login))
#          @listPanelStr = @listPanelStr + "&nbsp;#{link_to image_tag('/themes/odotclassic/images/delete.png') , {:action => 'delete', :id => @model} , {:confirm => 'Are you sure you want to delete?'}}"
#        end
        
        @listPanelStr = @listPanelStr + "</td></tr>\n"
        count = count + 1  
      end
      @listPanelStr = @listPanelStr + "</table></div>\n"
   end
 
    def renderBasicListPanel_w_f_s(form_controller, form_action, columns_to_display, model_list, enable_pagination, pagination_model_list, options)
      @listPanelStr = "<script language='JavaScript' type='text/javascript'>function listformsubmit(actionval){alert('submittimg...'+actionval);document.listform.action=actionval;document.listform.submit;}</script>\n"
      @listPanelStr = @listPanelStr + "<div class='list'><table>"
      if(enable_pagination)
        @listPanelStr = @listPanelStr + "<tr><td class='pagination' colspan='#{columns_to_display.size+1}'>"
        pagination_html = pagination_links(pagination_model_list)
        if(pagination_html==nil)
        	pagination_html = ""
        end
	@listPanelStr = @listPanelStr + pagination_html        
        @listPanelStr = @listPanelStr + "</td></tr>"
      end
      for column in columns_to_display
        @listPanelStr = @listPanelStr + "<th>#{column.human_name}</th>"
      end  
      @listPanelStr = @listPanelStr + "<th>Actions</th>"  
      count=1
      rowtype="odd"
      for @model in model_list
        rowtype = get_row_type(count)
        @listPanelStr = @listPanelStr + "<tr class='#{rowtype}'>"
        for column in columns_to_display
          @listPanelStr = @listPanelStr + "<td>#{@model.send(column.name)}</td>"
        end
        @listPanelStr = @listPanelStr + "<td>"
        if canRequestLink(form_controller, "show")
          @listPanelStr = @listPanelStr + "<form name='listform' action='/#{form_controller}/show/#{@model.id}'/>"
           @listPanelStr = @listPanelStr + "&nbsp;<input type='image' src='/themes/odotclassic/images/show.png'/>" #{:action => 'show', :id => @model}}"
           @listPanelStr = @listPanelStr + "</form>"
           #onclick='javascript:listformsubmit(\"/#{form_controller}/show/#{@model.id}\");'

        end
        if canRequestLink(form_controller, "edit")
          @listPanelStr = @listPanelStr + "<form name='listform' action='/#{form_controller}/edit/#{@model.id}'/>"
           @listPanelStr = @listPanelStr + "&nbsp;<input type='image' src='/themes/odotclassic/images/edit.png'/>" #{:action => 'show', :id => @model}}"
           @listPanelStr = @listPanelStr + "</form>"
            #onclick='javascript:listformsubmit(\"/#{form_controller}/edit/#{@model.id}\");'
        end
        if canRequestLink(form_controller, "delete")
          @listPanelStr = @listPanelStr + "<form name='listform' action='/#{form_controller}/delete/#{@model.id}'/>"
           @listPanelStr = @listPanelStr + "&nbsp;<input type='image' src='/themes/odotclassic/images/delete.png'/>" #{:action => 'show', :id => @model}}"
           @listPanelStr = @listPanelStr + "</form>"
           #onclick='javascript:listformsubmit(\"/#{form_controller}/delete/#{@model.id}\");'
        end
           
        #@listPanelStr = @listPanelStr + "&nbsp;#{link_if_authorized image_submit_tag('/themes/odotclassic/images/edit.png'), {:action => 'edit', :id => @model}}"
        #@listPanelStr = @listPanelStr + "&nbsp;#{link_if_authorized image_submit_tag('/themes/odotclassic/images/delete.png') , {:action => 'delete', :id => @model} , {:confirm => 'Are you sure you want to delete?'}}"
        
        # special execution buttons for service control
        
        if(@options!=nil)
          @showexecute = @options['showexecute']
          if(@showexecute!=nil and @showexecute=='true')
            @hostname = @options['hostname']
            if(@hostname==nil)
              @hostname = ""
            end  

            if canRequestLink(form_controller, "execute")
               @listPanelStr = @listPanelStr + "<form name='listform' action='/#{form_controller}/execute/#{@model.id}?hn=#{@hostname}'/>"
               @listPanelStr = @listPanelStr + "&nbsp;<input type='image' src='/themes/odotclassic/images/go-next.png'/>" #{:action => 'show', :id => @model}}"
                #onclick='javascript:listformsubmit(\"/#{form_controller}/execute/#{@model.id}?hn=#{@hostname}\")};'
                @listPanelStr = @listPanelStr + "</form>"
            end
            
            #@listPanelStr = @listPanelStr + "&nbsp;#{link_if_authorized image_submit_tag('/themes/odotclassic/images/go-next.png') , {:action => 'execute', :id => @model, :hn=>@hostname}, {:confirm => 'Are you sure you want to run this command?'} }"
          end
        end

        
        @listPanelStr = @listPanelStr + "</td></tr>"
        count = count + 1  
      end
      @listPanelStr = @listPanelStr + "</table></div>"
   end
   
    def renderCreateNewPanel(form_parameter_map, form_element_list, form_title, model_name)
      @createNewPanelStr = ""
      @formElementStr =""
      count=1
      rowtype="odd"
      form_element_list.each {|form_element|

        rowtype = get_row_type(count)
        
        @type = form_element["type"]
        if(@type==nil)
          @type="text"
        end
        @label = form_element["label"]
        if(@label==nil)
          return "<font color='red'>Label not provided for Form element in Create New panel rendering..</font>"
        end  
        @name = form_element["name"]
        if(@name==nil)
          @name = @label
        end
        @size = form_element["size"]
        if(@size==nil)
          @size = "10"
        end
        @required = form_element["required"]
        @requiredStr="*"
        if(@required==nil or @required=="false")
          @requiredStr = ""
        end

        @cssstyle = form_element["cssstyle"]
        @form_element_string = "<input style='#{@cssstyle}' size='#{@size}' type='#{@type}' name='#{@name}'/>"
        if @type.upcase=='TEXTAREA'
          @rows = form_element["rows"]
          @cols = form_element["cols"]
          @form_element_string = "<textarea style='#{@cssstyle}' rows='#{@rows}' cols='#{@cols}' name='#{@name}'/></textarea>"
        end
        
        @formElementStr = @formElementStr + "<tr class='#{rowtype}'><td>#{@label} #{@requiredStr}</td><td>#{@form_element_string}</td></tr>"
        count = count +1
      }
      @formElementStr = "<table>" + @formElementStr + "</table>"
      @formElementStr =  @formElementStr + "<br/>&nbsp;<input type='submit' name='crnewform' value='Create New'/>"
      # image_submit_tag("/themes/odotclassic/images/save.gif", :border => 0)

      @form_tag_str = ""
      @form_controller = form_parameter_map["controller"]
      @form_action = form_parameter_map["action"]
      @action = "";
      if(@form_controller!=nil)
        @action = @action + @form_controller
      end
      if(@form_action!=nil)
        @action = @action + "/" +@form_action
      end
      if (@action==nil)
        @action="search"
      end
      @action= "/"+@action
          
      @form_method = form_parameter_map["method"]
      if (@form_method==nil)
        @form_method="post"
      end
      @form_tag_str = "<form action='#{@action}' name='newform' method='#{@form_method}'>" 
      
      @createNewPanelStr = "<font color='red'>" + error_messages_for(model_name)+ "</font>"
      @createNewPanelStr = @createNewPanelStr + '<div class="list">'
      @createNewPanelStr = @createNewPanelStr + @form_tag_str
      @createNewPanelStr = @createNewPanelStr + "<fieldset><legend>#{form_title}</legend>"
      @createNewPanelStr = @createNewPanelStr + @formElementStr
      @createNewPanelStr = @createNewPanelStr + '</fieldset></form><br/></div>'
      return @createNewPanelStr
   end 
   

    def renderEditPanel(form_parameter_map, form_element_list, form_title, 
                         model_name, model_obj, hidden_params, options)
      @createEditPanelStr = ""
      @formElementStr =""
      count=1
      rowtype="odd"
      form_element_list.each {|form_element|

        rowtype = get_row_type(count)

        @type = form_element["type"]
        if(@type==nil)
          @type="text"
        end
        @label = form_element["label"]
        if(@label==nil)
          return "<font color='red'>Label not provided for Form element in Create New panel rendering..</font>"
        end  
        @name = form_element["name"]
        if(@name==nil)
          @name = @label
        end
        @size = form_element["size"]
        if(@size==nil)
          @size = "10"
        end
        @required = form_element["required"]
        @requiredStr="*"
        if(@required==nil or @required=="false")
          @requiredStr = ""
        end

        @value = form_element["value"]
        if(@value==nil)
          @value = ""
        end

        @form_element_string="<input size='#{@size}' type='#{@type}' name='#{@name}' value='#{@value}'/>";
        @cssstyle = form_element["cssstyle"]
        @form_element_string = "<input style='#{@cssstyle}' size='#{@size}' type='#{@type}' name='#{@name}' value='#{@value}'/>"
        if @type.upcase=='TEXTAREA'
          @rows = form_element["rows"]
          @cols = form_element["cols"]
          @form_element_string = "<textarea style='#{@cssstyle}' rows='#{@rows}' cols='#{@cols}' name='#{@name}'/></textarea>"
        end

        @readonly = form_element["readonly"]
        if @readonly!=nil and @readonly=='true'
          @form_element_string= "#{@value}"            
        end
  
        @formElementStr = @formElementStr + "<tr class='#{rowtype}'><td>#{@label} #{@requiredStr}</td><td>#{@form_element_string}</td></tr>"
        count = count +1
      }
      
      @save_string = "Save"
      
      if options!=nil
        @temp_string = options['save_string']
        if @temp_string!=nil
          @save_string = @temp_string
        end
      end
 
      @save_string = "<input type='submit' name='savebutton' value='#{@save_string}'/>"   #link_if_authorized submit_tag(@save_string)
           
      @formElementStr = "<table>" + @formElementStr + "</table>"
      #@formElementStr =  @formElementStr + "<br/>&nbsp;<input type='submit' name='savebutton' value='Save'/>"
      @formElementStr =  @formElementStr + "<br/>&nbsp;#{@save_string}"
      # image_submit_tag("/themes/odotclassic/images/save.gif", :border => 0)

      @form_tag_str = ""
      @form_controller = form_parameter_map["controller"]
      @form_action = form_parameter_map["action"]
      @action = "";
      if(@form_controller!=nil)
        @action = @action + @form_controller
      end
      if(@form_action!=nil)
        @action = @action + "/" +@form_action
      end
      if (@action==nil)
        @action="search"
      end
      @action= "/"+@action
          
      @form_method = form_parameter_map["method"]
      if (@form_method==nil)
        @form_method="post"
      end
      @form_tag_str = "<form action='#{@action}' name='editform' method='#{@form_method}'>" 
      
      @createEditPanelStr = "<font color='red'>" + error_messages_for(model_name)+ "</font>"
      @createEditPanelStr = @createEditPanelStr + '<div class="list">'
      @createEditPanelStr = @createEditPanelStr + @form_tag_str
      @createEditPanelStr = @createEditPanelStr + "<fieldset><legend>#{form_title}</legend>"
      @createEditPanelStr = @createEditPanelStr + @formElementStr
      
      # Now get hidden parameters
      
     if hidden_params!=nil
       hidden_params.each_key {|hidden_params_key|
          hidden_params_val = hidden_params[hidden_params_key]
          @createEditPanelStr = @createEditPanelStr + "<input type='hidden' name='#{hidden_params_key}' value='#{hidden_params_val}'/>" 
        }
     end   
      
      @createEditPanelStr = @createEditPanelStr + '</fieldset></form><br/></div>'
      return @createEditPanelStr
   end 
   
   
   def renderShowPanelAuto(content_columns, model, page_title, model_name)
     @viewPanelStr = ""
     @formElementStr =""
       
      count=1
      rowtype="odd"
      for column in content_columns
        rowtype = get_row_type(count)

        @label = column.human_name
        @value = model.send(column.name)
        @formElementStr = @formElementStr + "<tr class='#{rowtype}'><td>#{@label}</td><td> #{@value}</td></tr>"
        count = count +1
      end
      @formElementStr = "<table>" + @formElementStr + "</table>"
      @viewPanelStr = @viewPanelStr + '<div class="list">'
      @viewPanelStr = @viewPanelStr + "<fieldset><legend>#{page_title}</legend>"
      @viewPanelStr = @viewPanelStr + @formElementStr
      @viewPanelStr = @viewPanelStr + '</fieldset><br/></div>'
      return @viewPanelStr
    
   end
   
   def renderCreateNewPanelAuto(form_parameter_map, content_columns, form_title, model_name)
      @createNewPanelStr = ""
      @formElementStr =""
      count=1
      rowtype="odd"
      for column in content_columns
      
        rowtype = get_row_type(count)

        @type = "text"
        if(@type==nil)
          @type="text"
        end
        @label = column.human_name
        if(@label==nil)
          return "<font color='red'>Label not provided for Form element in Create New panel rendering..</font>"
        end  
        @column_name = column.name
        @name = @column_name
        if(@name==nil)
          @name = @label
        end
        @size = "10"
        @value = ""
        if(@name=='created_at'  or @name=='updated_at')
          @value= Time.now
          @size="25"
        end
        
        if(@size==nil)
          @size = "10"
        end
        @required = "true"
        @requiredStr="*"
        if(@required==nil or @required=="false")
          @requiredStr = ""
        end

        @formElementStr = @formElementStr + "<tr class='#{rowtype}'><td>#{@label} #{@requiredStr}</td><td><input size='#{@size}' type='#{@type}' name='#{@name}' value='#{@value}'/></td></tr>"
        count = count +1
      end
      @formElementStr = "<table>" + @formElementStr + "</table>"
      @formElementStr =  @formElementStr + "<br/>&nbsp;<a href='javascript:document.newform.submit();'>Create</a>"
      # image_submit_tag("/themes/odotclassic/images/save.gif", :border => 0)

      @form_tag_str = ""
      @form_controller = form_parameter_map["controller"]
      @form_action = form_parameter_map["action"]
      @action = "";
      if(@form_controller!=nil)
        @action = @action + @form_controller
      end
      if(@form_action!=nil)
        @action = @action + "/" +@form_action
      end
      if (@action==nil)
        @action="search"
      end
      @action= "/"+@action
          
      @form_method = form_parameter_map["method"]
      if (@form_method==nil)
        @form_method="post"
      end
      @form_tag_str = "<form action='#{@action}' name='newform' method='#{@form_method}'>" 
      
      @createNewPanelStr = "<font color='red'>" + error_messages_for(model_name)+ "</font>"
      @createNewPanelStr = @createNewPanelStr + '<div class="list">'
      @createNewPanelStr = @createNewPanelStr + @form_tag_str
      @createNewPanelStr = @createNewPanelStr + "<fieldset><legend>#{form_title}</legend>"
      @createNewPanelStr = @createNewPanelStr + @formElementStr
      @createNewPanelStr = @createNewPanelStr + '</fieldset></form><br/></div>'
      return @createNewPanelStr
    
  end
     
  
  def get_permission(module_name, data_access_action)
    @permission = Permission.find(:first, :conditions => [ "controller =? and action=?", module_name, data_access_action])
    return @permission  
  end   

  def get_data_permission(perm_id, role_id)
    @data_permission = Dataaccess.find(:first, :conditions => [ "role_id =? and permission_id=?", role_id, perm_id])
    return @data_permission  
  end   

  def find_by_rima(role_id, module_name, data_access_action)
      data_collection_from_db = DataCollection.find_all_by_role_id_and_module_and_action(role_id, module_name, data_access_action)
      # TODO this can be improved, you can directly collect the collection_id from returned records
      saved_data_collection = Array.new()
      count=0
      
      if(data_collection_from_db!=nil)
        for data_collection in data_collection_from_db
          saved_data_collection.push(data_collection.collection_id) 
        end  
      end
      return saved_data_collection
  end
  
  def get_model_record(model_name, id)
    
  end
  
  def get_row_type(count)
    if isodd(count)
      rowtype="odd"
    else
      rowtype="even"  
    end
    rowtype
  end
end